﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using BusinessFacade;
using EntityManage;

public partial class Modules_Personal_FirstAssignList : System.Web.UI.Page
{
    IPerf_Personal_TargetOwnerHandler toHandler = new Perf_Personal_TargetOwnerManage();
    ISys_UserHandler userHandler = new Sys_UserManage();
    ISys_OrganizationHandler orgHandler = new Sys_OrganizationManage();
    ISys_OrganizationHandlerExt orgExtHandler = new Sys_OrganizationManageExt();
    ISys_PostHandler postHandler = new Sys_PostManage();
    IPerf_Personal_FirstAssignHandler firstAssignHandler = new Perf_Personal_FirstAssignManage();
    IPerf_Flow_TraceHandler flowTraceHandler = new Perf_Flow_TraceManage();
    IPerf_Personal_ModTargetHandler modTargetHandler = new Perf_Personal_ModTargetManage();
    IPerf_Personal_ModTargetDtlHandler modTargetDtlHandler = new Perf_Personal_ModTargetDtlManage();
    IPerf_Personal_TargetHandler targetHandler = new Perf_Personal_TargetManage();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckPurviews())
        {
            Response.Redirect("~/Login.aspx");
        }
        if (!IsPostBack)
        {
            ViewState["OrderBy"] = "Id";
            ViewState["Accending"] = "desc";

            dataBind(string.Empty, null);
          
        }
    }

    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("302010"))
            {
                btnCreate.Visible = strPur.Contains("302011");
                btnApporval.Visible = strPur.Contains("302013");
            }
            else
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }

    #region DataBind
    
    /// <summary>
    /// 初始化岗位信息表
    /// </summary>
    private void dataBind(string whereClause, SqlParameter[] parms)
    {
        try
        {
            FillSearchDDL();

            SqlParameter[] parms2 = null;
            int counter = 0;
            DataTable dt = new DataTable();

            if (whereClause != string.Empty)
            {
                dt = firstAssignHandler.GetPerf_Personal_FirstAssignByPageList(whereClause, parms, ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
                whereClause = "1=1";
                ProcessParms(ref whereClause, ref parms2);
                counter = firstAssignHandler.GetCounter(whereClause, parms2);
            }
            else
            {
                dt = firstAssignHandler.GetPerf_Personal_FirstAssignByPageList(ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
                counter = firstAssignHandler.GetCounter();
            }

            this.AspNetPager.RecordCount = counter;
            gvFirstAssignList.DataSource = dt;
            gvFirstAssignList.DataBind();
        }
        catch
        {
            Jscript.AlertInAjax("連接錯誤!", UpdatePanel1);
            return;
        }
    }

    /// <summary>
    /// 条件参数处理
    /// </summary>
    /// <param name="whereClause"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string whereClause, ref SqlParameter[] parms)
    {
        List<SqlParameter> lstParm = new List<SqlParameter>();

        if (ViewState["SearchOrgID"] != null)
        {
            whereClause += " and Org_ID = @Org_ID";
            lstParm.Add(new SqlParameter("@Org_ID", int.Parse(ViewState["SearchOrgID"].ToString())));
        }

        if (ViewState["SearchPostID"] != null)
        {
            whereClause += " and Post_ID = @Post_ID";
            lstParm.Add(new SqlParameter("@Post_ID", int.Parse(ViewState["SearchPostID"].ToString())));
        }

        if (ViewState["SearchTOID"] != null)
        {
            whereClause += " and TargetOwner_ID = @TargetOwner_ID";
            lstParm.Add(new SqlParameter("@TargetOwner_ID", int.Parse(ViewState["SearchTOID"].ToString())));
        }

        if (ViewState["SearchStatus"] != null)
        {
            whereClause += " and Status = @Status";
            lstParm.Add(new SqlParameter("@Status", int.Parse(ViewState["SearchStatus"].ToString())));
        }

        parms = lstParm.ToArray();
    }

    private void FillSearchDDL()
    {
        FillSearchOrg();
        FillSearchPost();
        FillSearchTO();
        FillSearchStatus();
    }

    private void FillSearchOrg()
    {
        DataTable dt = orgHandler.GetSys_OrganizationList(" Status = @Status and (Type = @Type1 or Type = @Type2)", new SqlParameter[]{
            new SqlParameter("@Status",(int)Enums.OrgStatus.Valid), new SqlParameter("@Type1", (int)Enums.OrgType.ICU), new SqlParameter("@Type2", (int)Enums.OrgType.Office)}, " Name asc");
        ddlSearchOrg.DataTextField = "Name";
        ddlSearchOrg.DataValueField = "ID";
        ddlSearchOrg.DataSource = dt;
        ddlSearchOrg.DataBind();
        ddlSearchOrg.Items.Insert(0, new ListItem("全部....", "0"));
    }

    private void FillSearchPost()
    {
        DataTable dt = postHandler.GetSys_PostList(" Status = @Status", new SqlParameter[]{ new SqlParameter("@Status", (int)Enums.NormalStatus.Vallid)}, " Name asc");
        ddlSearchPost.DataTextField = "Name";
        ddlSearchPost.DataValueField = "ID";
        ddlSearchPost.DataSource = dt;
        ddlSearchPost.DataBind();
        ddlSearchPost.Items.Insert(0, new ListItem("全部....","0"));
    }


    private void FillSearchTO()
    {
        DataTable dt = toHandler.GetPerf_Personal_TargetOwnerList();
        ddlSearchTo.DataTextField = "Name";
        ddlSearchTo.DataValueField = "ID";
        ddlSearchTo.DataSource = dt;
        ddlSearchTo.DataBind();
        ddlSearchTo.Items.Insert(0, new ListItem("全部....", "0"));
    }

    private void FillSearchStatus()
    {
        DataTable dtStatus = new DataTable();
        dtStatus.Columns.Add("Value");
        dtStatus.Columns.Add("Name");
        DataRow drStatus;

        drStatus = dtStatus.NewRow();
        drStatus[0] = "-1";
        drStatus[1] = "全部....";
        dtStatus.Rows.Add(drStatus);

        drStatus = dtStatus.NewRow();
        drStatus[0] = "0";
        drStatus[1] = Enums.GetPersonalFirstAssignStatus(Enums.PersonalFirstAssignStatus.NewAdded);
        dtStatus.Rows.Add(drStatus);

        drStatus = dtStatus.NewRow();
        drStatus[0] = "1";
        drStatus[1] = Enums.GetPersonalFirstAssignStatus(Enums.PersonalFirstAssignStatus.Assigned);
        dtStatus.Rows.Add(drStatus);

        ddlSearchStatus.DataSource = dtStatus;
        ddlSearchStatus.DataTextField = "Name";
        ddlSearchStatus.DataValueField = "Value";
        ddlSearchStatus.DataBind();
    }

    #endregion

    #region gvFirstAssignList

    protected void gvFirstAssignList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //
        if (e.CommandName == "del")
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString().Trim());
            try
            {
                // 判断是否新增状态
                Perf_Personal_FirstAssignQuery query = firstAssignHandler.GetPerf_Personal_FirstAssignQuery(id);
                if (query != null && query.Status != (int)Enums.PersonalFirstAssignStatus.NewAdded)
                {
                    Jscript.AlertInAjax("非新增状态，不能删除!", UpdatePanel1);
                    return;
                }

                firstAssignHandler.DeletePerf_Personal_FirstAssign(id);
                Jscript.AlertInAjax("操作成功!", UpdatePanel1);
                RefreshDataGridView();
            }
            catch
            {
                Jscript.AlertInAjax("操作失败!", UpdatePanel1);
            }
        }
    }

    protected void gvFirstAssignList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ImageButton ibtnDel = (ImageButton)e.Row.FindControl("ibtnDelete");
            if (Session["UserPurviews"] != null)
            {
                if (Session["UserPurviews"].ToString().Contains("302012"))//删除
                {
                    ibtnDel.Visible = true;
                }
                else
                {
                    ibtnDel.Visible = false;
                }
            }

            HtmlInputCheckBox chkSelected = (HtmlInputCheckBox)e.Row.FindControl("chkSelected");
            if (int.Parse(e.Row.Cells[7].Text.Trim()) == (int)Enums.PersonalFirstAssignStatus.NewAdded)
                chkSelected.Visible = true;
            else
                chkSelected.Visible = false;

            if (e.Row.RowIndex > -1)
            {
                // 分配人
                Sys_UserQuery userQuery = userHandler.GetSys_UserQuery(int.Parse(e.Row.Cells[2].Text));
                if (userQuery != null)
                    e.Row.Cells[2].Text = userQuery.Name;

                // 单位
                Sys_OrganizationQuery orgQuery = orgHandler.GetSys_OrganizationQuery(int.Parse(e.Row.Cells[3].Text));
                if (orgQuery != null)
                    e.Row.Cells[3].Text = orgQuery.Name;

                // 岗位
                Sys_PostQuery postQuery = postHandler.GetSys_PostQuery(int.Parse(e.Row.Cells[4].Text));
                if (postQuery != null)
                    e.Row.Cells[4].Text = postQuery.Name;

                // 指标套
                Perf_Personal_TargetOwnerQuery toQuery = toHandler.GetPerf_Personal_TargetOwnerQuery(int.Parse(e.Row.Cells[5].Text));
                if (toQuery != null)
                    e.Row.Cells[5].Text = toQuery.Name;

                // 状态
                Enums.PersonalFirstAssignStatus toStatus = (Enums.PersonalFirstAssignStatus)int.Parse(e.Row.Cells[7].Text);
                e.Row.Cells[7].Text = Enums.GetPersonalFirstAssignStatus(toStatus);
                ibtnDel.Visible = toStatus == Enums.PersonalFirstAssignStatus.NewAdded;
            }
        }
    }

    protected void gvFirstAssignList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        RefreshDataGridView();
    }

    #endregion

    #region Button
    
    
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (!ddlSearchOrg.SelectedValue.Equals("0"))
            ViewState["SearchOrgID"] = ddlSearchOrg.SelectedValue;
        else
            ViewState["SearchOrgID"] = null;

        if (!ddlSearchPost.SelectedValue.Equals("0"))
            ViewState["SearchPostID"] = ddlSearchPost.SelectedValue;
        else
            ViewState["SearchPostID"] = null;

        if (!ddlSearchTo.SelectedValue.Equals("0"))
            ViewState["SearchTOID"] = ddlSearchTo.SelectedValue;
        else
            ViewState["SearchTOID"] = null;

        if (!ddlSearchStatus.SelectedValue.Equals("-1"))
            ViewState["SearchStatus"] = ddlSearchStatus.SelectedValue;
        else
            ViewState["SearchStatus"] = null;

        RefreshDataGridView();
    }

    protected void CreateButton_Click(object sender, EventArgs e)
    {
        RefreshDataGridView();
    }
    protected void AspNetPager_PageChanged(object src, EventArgs e)
    {
        RefreshDataGridView();
    }

    //protected void ApprovalButton_Click(object sender, EventArgs e)
    //{
    //    if (Session["UserPurviews"] != null && Session["UserPurviews"].ToString().Contains("302013"))
    //    {
    //        List<string> ids = new List<string>();
    //        for (int i = 0; i < gvFirstAssignList.Rows.Count; i++ )
    //        {
    //            if (gvFirstAssignList.Rows[i].RowType == DataControlRowType.DataRow)
    //            {
    //                HtmlInputCheckBox chkb = (HtmlInputCheckBox)gvFirstAssignList.Rows[i].FindControl("chkSelected");
    //                if (chkb.Checked)
    //                    ids.Add(chkb.Value);
    //            }
    //        }
    //        if (ids.Count > 0)
    //        {
                
    //            foreach (string id in ids)
    //            {
    //                int intId = int.Parse(id);
    //                Perf_Personal_FirstAssignQuery query = firstAssignHandler.GetPerf_Personal_FirstAssignQuery(intId);
    //                if (query != null && query.Status == (int)Enums.PersonalFirstAssignStatus.NewAdded)
    //                {
    //                    Perf_Flow_TraceQuery ftQuery = new Perf_Flow_TraceQuery();
    //                    ftQuery.Flow_ID = (int)Enums.PerfFlowIDs.PersonalFirstAssignApproval;
    //                    ftQuery.Business_ID = query.ID;
    //                    ftQuery.URL = Enums.Personal_FirstAssign_Flow_Form_URL;
    //                    ftQuery.Begin_Time = DateTime.Now;
    //                    ftQuery.Current_Step = 0;

    //                    int flowTraceId = 0;
    //                    flowTraceHandler.InsertPerf_Flow_Trace(ftQuery, ref flowTraceId);

    //                    // 更新状态和流程ID
    //                    if (flowTraceId != 0)
    //                    {
    //                        query.Status = (int)Enums.PersonalFirstAssignStatus.OnFlowing;
    //                        query.Flow_Trace_ID = flowTraceId;
    //                        firstAssignHandler.UpdatePerf_Personal_FirstAssign(query);

    //                        // 修改个别指标修改表的Trace_ID
    //                        Perf_Personal_ModTargetQuery[] modTargetList = modTargetHandler.GetPerf_Personal_ModTargetQueryList(
    //                            "FirstAssign_ID = @FirstAssign_ID and Status = @Status and Org_ID = @Org_ID and Post_ID = @Post_ID"
    //                            , new SqlParameter[]{new SqlParameter("@FirstAssign_ID", query.ID), 
    //                                new SqlParameter("@Status", (int)Enums.PersonalFirstAssignStatus.NewAdded),
    //                            new SqlParameter("@Org_ID", query.Org_ID),
    //                            new SqlParameter("@Post_ID", query.Post_ID)});
    //                        if (modTargetList != null && modTargetList.Length > 0)
    //                        {
    //                            foreach (Perf_Personal_ModTargetQuery modTargetQuery in modTargetList)
    //                            {
    //                                modTargetQuery.Status = query.Status;
    //                                modTargetQuery.Flow_Trace_ID = flowTraceId;
    //                                modTargetHandler.UpdatePerf_Personal_ModTarget(modTargetQuery);
    //                            }
    //                        }
    //                    }
    //                    else
    //                    {
    //                        Jscript.AlertInAjax("操作失败", UpdatePanel1);
    //                        return;
    //                    }
    //                }
    //            }
    //            Jscript.AlertInAjax("操作成功", UpdatePanel1);
    //            RefreshDataGridView();
    //        }
    //        else
    //        {
    //            Jscript.AlertInAjax("请选择要呈批的记录", UpdatePanel1);
    //        }
    //    }
    //    else
    //    {
    //        Jscript.AlertInAjax("无此权限", UpdatePanel1);
    //    }
    //}

    protected void ApprovalButton_Click(object sender, EventArgs e)
    {
        if (Session["UserPurviews"] != null && Session["UserPurviews"].ToString().Contains("302013"))
        {
            int userId = int.Parse(Session["CurrentUserID"].ToString());
            List<string> ids = new List<string>();
            for (int i = 0; i < gvFirstAssignList.Rows.Count; i++)
            {
                if (gvFirstAssignList.Rows[i].RowType == DataControlRowType.DataRow)
                {
                    HtmlInputCheckBox chkb = (HtmlInputCheckBox)gvFirstAssignList.Rows[i].FindControl("chkSelected");
                    if (chkb.Checked)
                        ids.Add(chkb.Value);
                }
            }
            if (ids.Count > 0)
            {
                foreach (string id in ids)
                {
                    int intId = int.Parse(id);
                    Perf_Personal_FirstAssignQuery query = firstAssignHandler.GetPerf_Personal_FirstAssignQuery(intId);
                    if (query != null && query.Status == (int)Enums.PersonalFirstAssignStatus.NewAdded)
                    {
                        // 将该单位下该岗位的人查出来，并添加到分配指标修改表和子表
                        string orgIds = orgExtHandler.GetAllChildIdsByParentID(query.Org_ID);
                        orgIds = (orgIds.Length > 0 ? orgIds + "," + query.Org_ID : query.Org_ID.ToString());
                        Sys_UserQuery[] userList = userHandler.GetSys_UserQueryList(" (Org_ID in (" + orgIds + ") or Org_ID2 in (" + orgIds + ")) and Status = @Status"
                            , new SqlParameter[] { new SqlParameter("@Status", (int)Enums.NormalStatus.Vallid)});
                        List<string> orgIdList = new List<string>();
                        orgIdList.AddRange(orgIds.Split(','));
                        if (userList != null && userList.Length > 0)
                        {
                            foreach (Sys_UserQuery user in userList)
                            {
                                int userOrgId = (user.Org_ID2 != 0 ? user.Org_ID2 : user.Org_ID);
                                int userPostId = (user.Post_ID2 != 0 ? user.Post_ID2 : user.Post_ID);

                                if (orgIdList.Contains(userOrgId.ToString()) && query.Post_ID == userPostId)
                                {
                                    // 添加到分配指标修改表
                                    Perf_Personal_ModTargetQuery modTargetQuery = new Perf_Personal_ModTargetQuery();
                                    modTargetQuery.Org_ID = query.Org_ID;
                                    modTargetQuery.Post_ID = query.Post_ID;
                                    modTargetQuery.TargetUser_ID = user.ID;
                                    modTargetQuery.TargetOwner_ID = query.TargetOwner_ID;
                                    modTargetQuery.FirstAssign_ID = query.ID;
                                    modTargetQuery.Create_Time = DateTime.Now;
                                    modTargetQuery.User_ID = userId;
                                    modTargetQuery.Status = (int)Enums.PersonalModTargetStatus.NewAssign;
                                    int modTargetId = 0;
                                    modTargetHandler.InsertPerf_Personal_ModTarget(modTargetQuery, ref modTargetId);

                                    // 添加子表记录
                                    if (modTargetId != 0)
                                    {
                                        Perf_Personal_TargetQuery[] targetList = targetHandler.GetPerf_Personal_TargetQueryList(
                                            " TargetOwner_ID = @TargetOwner_ID and Status = @Status",
                                            new SqlParameter[] { new SqlParameter("@TargetOwner_ID", query.TargetOwner_ID),new SqlParameter("@Status", (int)Enums.NormalStatus.Vallid) });
                                        if (targetList != null && targetList.Length > 0)
                                        {
                                            foreach (Perf_Personal_TargetQuery targetQuery in targetList)
                                            {
                                                Perf_Personal_ModTargetDtlQuery modTargetDtlQuery = new Perf_Personal_ModTargetDtlQuery();
                                                modTargetDtlQuery.ModTarget_ID = modTargetId;
                                                modTargetDtlQuery.Type = (int)Enums.PersonalModTargetType.Original;
                                                modTargetDtlQuery.Target_ID = targetQuery.ID;
                                                modTargetDtlHandler.InsertPerf_Personal_ModTargetDtl(modTargetDtlQuery);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        // 更新状态
                        query.Status = (int)Enums.PersonalFirstAssignStatus.Assigned;
                        firstAssignHandler.UpdatePerf_Personal_FirstAssign(query);
                    }
                }
                Jscript.AlertInAjax("操作成功", UpdatePanel1);
                RefreshDataGridView();
            }
            else
            {
                Jscript.AlertInAjax("请选择要呈批的记录", UpdatePanel1);
            }
        }
        else
        {
            Jscript.AlertInAjax("无此权限", UpdatePanel1);
        }
    }

    #endregion

    private void RefreshDataGridView()
    {
        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParms(ref clause, ref parms);
        dataBind(clause, parms);
    }
}
